#!/bin/bash

function make_dirs () {
  [[ -d /run/pi-mon ]] || (sudo mkdir /run/pi-mon; sudo chgrp $USER /run/pi-mon; sudo chmod 770 /run/pi-mon) 
}

function make_fs () {
  # Initialise the test file systems

  for v in volume1 volume2
  do
    (mount | grep -ql $v) && continue
    [[ -f /var/tmp/$v ]] || dd if=/dev/zero of=/var/tmp/$v bs=1M count=10
    mkfs -F -t ext4 /var/tmp/$v
    [[ -d /media/$v ]] || sudo mkdir -p /media/$v
    sudo mount -o loop /var/tmp/$v /media/$v
  done
}

function make_web () {
  # Prepare the web server file hierarchy (of sorts)

  [[ -d $HOME/web ]] || mkdir $HOME/web
  cat >$HOME/web/index.html <<END
<html>
  <head>
    <title>Raspberry Pi</title>
  </head>
  <body>
    <h1>Raspberry Pi</h1>
    <p>Hallo Welt!</p>
  </body>
</html> 
END
}

function start_web () {
  # Start the web server in the background
  [[ -d $HOME/web ]] || (echo >&2 "$0: web server directory missing"; exit 1)
  (cd $HOME/web;
   python /usr/lib/python2.7/SimpleHTTPServer.py >/dev/null 2>&1 &
   echo $!) >/run/pi-mon/httpd.pid
}

function start_tests () {
  pi-mon-run-tests &
  echo $! >/run/pi-mon/pi-mon.pid
}

function stop_process () {
  [[ -r /run/pi-mon/$1.pid ]] || return
  pid=$(cat /run/pi-mon/$1.pid)
  kill -TERM $pid || echo >&2 "$0: couldn't kill $1 process"
  rm -f /run/pi-mon/$1.pid
}

function stop_web () {
  stop_process httpd
}

function stop_tests () {
  stop_process pi-mon
}

function status () {
  for p in pi-mon httpd
  do
    ([[ -r /run/pi-mon/$p.pid ]] \
     && kill -0 $(cat /run/pi-mon/$p.pid)) && echo "$p running" || echo "$p not running"
  done
}

case $1 in
  setup)     make_dirs; make_fs; make_web ;;
  start-web) start_web ;;
  stop-web)  stop_web ;;
  start)     start_tests ;;
  stop)      stop_tests ;;
  status)    status ;;
  *)	     echo >&2 "$0: invalid command $1"; exit 1 ;;
esac

